package be.pluyckx.batteryprogress.data.history.snapshot;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import be.pluyckx.batteryprogress.database.BatteryLevelFileStorage;
import be.pluyckx.batteryprogress.utils.StringUtils;

/**
 * Created by Philip on 28/08/13.
 */
public class ProcessItem implements BatteryLevelFileStorage.FileWritable {
  public static final int FORMAT_PROCESS_NAME_PID = 0;
  public static final int FORMAT_PROCESS_NAME = 1;
  public static final int FORMAT_PROCESS_PID = 2;

  private final String mProccessName;
  private final int mPid;
  private final List<ServiceItem> mServices;

  public ProcessItem(int pid, String proccessName) {
    mPid = pid;
    mProccessName = proccessName;
    mServices = new ArrayList<ServiceItem>();
  }

  public Iterator<ServiceItem> iterateServices() {
    return mServices.iterator();
  }

  void addService(ServiceItem service) {
    mServices.add(service);
  }

  public String getProccessName() {
    return mProccessName;
  }

  public int getProcessId() {
    return mPid;
  }

  @Override
  public int streamSize() {
    int size = StringUtils.lengthUTF(mProccessName, true) + Integer.SIZE / 8 * 2;

    for (ServiceItem si : mServices) {
      size += si.streamSize();
    }

    return size;
  }

  @Override
  public void write(DataOutputStream d) throws IOException {
    d.writeInt(mPid);
    d.writeUTF(mProccessName);
    d.writeInt(mServices.size());
    for (ServiceItem i : mServices) {
      i.write(d);
    }
  }

  public ProcessItem(DataInputStream dis) throws IOException {
    mPid = dis.readInt();
    mProccessName = dis.readUTF();
    int size = dis.readInt();
    mServices = new ArrayList<ServiceItem>(size);
    for (int i = 0; i < size; i++) {
      mServices.add(new ServiceItem(dis));
    }
  }

  public String toString(int format) {
    switch (format) {
      case FORMAT_PROCESS_NAME:
        return getProccessName();
      case FORMAT_PROCESS_PID:
        return Integer.toString(getProcessId());
      default:
        StringBuilder sb = new StringBuilder();
        sb.append(mProccessName);
        sb.append(" (");
        sb.append(Integer.toString(getProcessId()));
        sb.append(")");
        return sb.toString();
    }
  }
}